using Microsoft.AspNetCore.Mvc;
using JGSY.CMS.LowCode.Platform.Infrastructure.Configuration;

namespace JGSY.CMS.LowCode.Platform.Controllers;

/// <summary>
/// 系统配置示例控制器 - 展示如何使用 EnhancedConfigurationProcessor
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class ConfigExampleController : ControllerBase
{
    private readonly ILogger<ConfigExampleController> _logger;

    public ConfigExampleController(ILogger<ConfigExampleController> logger)
    {
        _logger = logger;
    }

    /// <summary>
    /// 获取数据库配置信息
    /// </summary>
    /// <returns>数据库配置</returns>
    [HttpGet("database-config")]
    public IActionResult GetDatabaseConfig()
    {
        try
        {
            var dbType = ConfigurationAccessor.MainDatabaseType;
            var connectionString = EnhancedConfigurationProcessor.GetDatabaseConnectionString(dbType);
            
            return Ok(new
            {
                DatabaseType = dbType,
                ConnectionString = MaskSensitiveInfo(connectionString),
                Timestamp = DateTime.UtcNow
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取数据库配置失败");
            return StatusCode(500, "获取数据库配置失败");
        }
    }

    /// <summary>
    /// 获取缓存配置信息
    /// </summary>
    /// <returns>缓存配置</returns>
    [HttpGet("cache-config")]
    public IActionResult GetCacheConfig()
    {
        try
        {
            var (type, connectionString, options) = EnhancedConfigurationProcessor.ProcessCacheConfiguration();
            
            return Ok(new
            {
                CacheType = type,
                ConnectionString = MaskSensitiveInfo(connectionString),
                Options = options,
                Timestamp = DateTime.UtcNow
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取缓存配置失败");
            return StatusCode(500, "获取缓存配置失败");
        }
    }

    /// <summary>
    /// 获取云存储配置信息
    /// </summary>
    /// <returns>云存储配置</returns>
    [HttpGet("storage-config")]
    public IActionResult GetStorageConfig()
    {
        try
        {
            var (provider, settings) = EnhancedConfigurationProcessor.ProcessCloudStorageConfiguration();
            
            // 掩码敏感信息
            var maskedSettings = settings.ToDictionary(
                kvp => kvp.Key,
                kvp => kvp.Key.Contains("Secret") || kvp.Key.Contains("Key") ? "****" : kvp.Value
            );
            
            return Ok(new
            {
                Provider = provider,
                Settings = maskedSettings,
                Timestamp = DateTime.UtcNow
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取云存储配置失败");
            return StatusCode(500, "获取云存储配置失败");
        }
    }

    /// <summary>
    /// 获取权限配置信息
    /// </summary>
    /// <returns>权限配置</returns>
    [HttpGet("permission-config")]
    public IActionResult GetPermissionConfig()
    {
        try
        {
            var (enabled, defaultRoles, adminRoles, strictMode) = EnhancedConfigurationProcessor.ProcessPermissionConfiguration();
            
            return Ok(new
            {
                Enabled = enabled,
                DefaultRoles = defaultRoles,
                AdminRoles = adminRoles,
                StrictMode = strictMode,
                Timestamp = DateTime.UtcNow
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取权限配置失败");
            return StatusCode(500, "获取权限配置失败");
        }
    }

    /// <summary>
    /// 获取CORS配置信息
    /// </summary>
    /// <returns>CORS配置</returns>
    [HttpGet("cors-config")]
    public IActionResult GetCorsConfig()
    {
        try
        {
            var (enabled, allowedOrigins, allowedMethods, allowedHeaders, allowCredentials) = EnhancedConfigurationProcessor.ProcessCorsConfiguration();
            
            return Ok(new
            {
                Enabled = enabled,
                AllowedOrigins = allowedOrigins,
                AllowedMethods = allowedMethods,
                AllowedHeaders = allowedHeaders,
                AllowCredentials = allowCredentials,
                Timestamp = DateTime.UtcNow
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取CORS配置失败");
            return StatusCode(500, "获取CORS配置失败");
        }
    }

    /// <summary>
    /// 验证配置完整性
    /// </summary>
    /// <param name="configType">配置类型</param>
    /// <returns>验证结果</returns>
    [HttpGet("validate/{configType}")]
    public IActionResult ValidateConfig(string configType)
    {
        try
        {
            var (isValid, errors) = EnhancedConfigurationProcessor.ValidateConfiguration(configType);
            
            return Ok(new
            {
                ConfigType = configType,
                IsValid = isValid,
                Errors = errors,
                ValidatedAt = DateTime.UtcNow
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "验证配置失败: {ConfigType}", configType);
            return StatusCode(500, $"验证配置失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取所有配置的汇总信息
    /// </summary>
    /// <returns>配置汇总</returns>
    [HttpGet("summary")]
    public IActionResult GetConfigSummary()
    {
        try
        {
            // 数据库配置
            var dbType = ConfigurationAccessor.MainDatabaseType;
            var (dbValid, dbErrors) = EnhancedConfigurationProcessor.ValidateConfiguration("database");
            
            // 缓存配置
            var (cacheType, _, cacheOptions) = EnhancedConfigurationProcessor.ProcessCacheConfiguration();
            var (cacheValid, cacheErrors) = EnhancedConfigurationProcessor.ValidateConfiguration("cache");
            
            // 存储配置
            var (storageProvider, storageSettings) = EnhancedConfigurationProcessor.ProcessCloudStorageConfiguration();
            var (storageValid, storageErrors) = EnhancedConfigurationProcessor.ValidateConfiguration("cloudstorage");
            
            // 权限配置
            var (permissionEnabled, _, _, strictMode) = EnhancedConfigurationProcessor.ProcessPermissionConfiguration();
            var (permissionValid, permissionErrors) = EnhancedConfigurationProcessor.ValidateConfiguration("permission");
            
            // CORS配置
            var (corsEnabled, allowedOrigins, _, _, _) = EnhancedConfigurationProcessor.ProcessCorsConfiguration();
            var (corsValid, corsErrors) = EnhancedConfigurationProcessor.ValidateConfiguration("cors");
            
            return Ok(new
            {
                GeneratedAt = DateTime.UtcNow,
                Database = new
                {
                    Type = dbType,
                    IsValid = dbValid,
                    Errors = dbErrors
                },
                Cache = new
                {
                    Provider = cacheType,
                    IsValid = cacheValid,
                    Errors = cacheErrors
                },
                Storage = new
                {
                    Provider = storageProvider,
                    IsValid = storageValid,
                    Errors = storageErrors
                },
                Permission = new
                {
                    Enabled = permissionEnabled,
                    StrictMode = strictMode,
                    IsValid = permissionValid,
                    Errors = permissionErrors
                },
                Cors = new
                {
                    Enabled = corsEnabled,
                    AllowedOriginsCount = allowedOrigins?.Length ?? 0,
                    IsValid = corsValid,
                    Errors = corsErrors
                },
                OverallStatus = new
                {
                    IsHealthy = dbValid && cacheValid && storageValid && permissionValid && corsValid,
                    TotalErrors = dbErrors.Count + cacheErrors.Count + storageErrors.Count + permissionErrors.Count + corsErrors.Count
                }
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取配置汇总失败");
            return StatusCode(500, "获取配置汇总失败");
        }
    }

    /// <summary>
    /// 掩码敏感信息
    /// </summary>
    /// <param name="value">原始值</param>
    /// <returns>掩码后的值</returns>
    private static string MaskSensitiveInfo(string value)
    {
        if (string.IsNullOrEmpty(value))
            return string.Empty;

        if (value.Contains("Password", StringComparison.OrdinalIgnoreCase) ||
            value.Contains("Pwd", StringComparison.OrdinalIgnoreCase))
        {
            var parts = value.Split(';');
            var maskedParts = new List<string>();

            foreach (var part in parts)
            {
                if (part.Contains("Password", StringComparison.OrdinalIgnoreCase) ||
                    part.Contains("Pwd", StringComparison.OrdinalIgnoreCase))
                {
                    var keyValue = part.Split('=');
                    if (keyValue.Length == 2)
                        maskedParts.Add($"{keyValue[0]}=****");
                    else
                        maskedParts.Add(part);
                }
                else
                {
                    maskedParts.Add(part);
                }
            }

            return string.Join(";", maskedParts);
        }

        return value;
    }
}
